package src.Fifteen;

import java.util.ArrayList;
import java.util.List;
public class ListAdd1 {
    private volatile static List list = new ArrayList<>();

    public void add(){
        list.add("haha");
    }

    public int size(){
        return list.size();
    }

    public static void main(String args[]){

        final ListAdd1 la = new ListAdd1();
        final Object lock = new Object();

        Thread t1 = new Thread(new Runnable(){
            @Override
            public void run() {
                synchronized(lock){
                    try {
                        for(int i = 0;i<=10;i++){
                            Thread.sleep(500);
                            la.add();
                            System.out.println("当前线程:" + Thread.currentThread().getName());
                            if(la.size()==5){
                                lock.notify();
                                System.out.println("唤醒通知已发出");
                            }
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        },"t1");

        Thread t2 = new Thread(new Runnable(){
            @Override
            public void run() {
                synchronized(lock){
                    if(list.size()!=5){
                        try {
                            lock.wait();
                            System.out.println("当前线程收到通知："+ Thread.currentThread().getName() +",list的size=5	线程停止，抛出异常");
                            throw new RuntimeException();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        },"t2");

        t2.start();
        t1.start();
    }
}

